package com.gujia.concurrent.exchange;

import oracle.jvm.hotspot.jfr.Producer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Exchanger;

public class ExchangeDemo {

    static Exchanger<List<String>> exchanger = new Exchanger();
    static class Producer extends Thread{
        private Exchanger<List<String>> exchanger;

        public Producer(Exchanger<List<String>> exchanger) {
            this.exchanger = exchanger;
        }

        public void run(){
            List<String> product = new ArrayList<String>();

            for (int i=0;i<10;i++){
                product.add("product->"+i);
            }

            try {
               List<String> result =  exchanger.exchange(product);
                System.out.println("生产者线程");
                for (int i=0;i<result.size();i++){
                   System.out.println("收到的金钱->"+result.get(i));
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


    static class Customer extends Thread{

        private Exchanger<List<String>> exchanger;

        public Customer(Exchanger<List<String>> exchanger) {
            this.exchanger = exchanger;
        }

        public void run(){
            List<String> customerMoney = new ArrayList<String>();

            for (int i=0;i<5;i++){
                customerMoney.add("customerMoney->"+i);
            }

            try {
                List<String> resP = exchanger.exchange(customerMoney);
                System.out.println("消费者线程");
                for (int j=0;j<resP.size();j++){
                    System.out.println("获得物品->"+resP.get(j));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }
    }


    public static void main(String[] args){

        new Producer(exchanger).start();
        new Customer(exchanger).start();

    }
}
